import React, { PureComponent } from 'react';
import _ from 'lodash';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Popconfirm } from 'antd';
import { PrimaryGhostC, AdvancedSearch, DATA_ENTRY, PrimaryC, TableC, InputNumberC, InfoTipsC } from '../../../comps';
import moment from 'moment';
import { exportFile } from '../../../utils/commonFunc';
import accounting from 'accounting';
import myStyle from './style.less';
import { connect } from 'dva';
@Form.create()
@connect(({ nonstandardValueReviewM }) => ({ nonstandardValueReviewM }))
export default class NonstandardLossRatioC extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      dataSource: [],
      isReset: false, // 是否点击重置
      selectedRowKeys: [], //勾选的数据
      isEdit: false, //是否处于编辑状态
      editDataSource: {}, //编辑前的数据
      isCheck: false, //true:勾选且包含了未复核,false:无勾选或勾选中不包含未复核。  逻辑： 没有勾选未复核的数据，一键确认按钮置灰
      isExportCheck: false, //true:勾选且包含了已复核,false:无勾选或勾选中不包含已复核。  逻辑： 没有勾选已复核的数据，导出按钮置灰
      checkConfirmArr: [], //一键确认所处理的数据，即已勾选的未复核的数据
      exportArr: [], //导出所处理的数据，即已勾选的已复核的数据
      expectedCreditLossesTemp: undefined, //编辑时预期信用损失比例的值
    };
  }
  componentDidMount() {
    this.getTableData();
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}
  // 获取表格数据
  getTableData = () => {
    this.setState(
      {
        columns: undefined,
        dataSource: undefined,
        isCheck: false,
        isExportCheck: false,
        selectedRowKeys: [], //勾选的key集合
        checkConfirmArr: [], //供一键确认的id集合
        exportArr: [], //供导出的id集合
        expectedCreditLossesTemp: undefined, //编辑时预期信用损失比例的值
      },
      () => {
        this.props.dispatch({
          type: 'nonstandardValueReviewM/getLossRatioTableData',
          payload: {
            currentPage: 1,
            numInPage: 999,
          },
          callback: (type, data) => {
            if (type == 'success') {
              // 成本摊余法
              data.columns &&
                data.columns.length &&
                data.columns.forEach((item) => {
                  if (item.dataIndex == 'assetType') {
                    // 资产类型
                    item.width = '12%';
                  }
                  if (item.dataIndex == 'tradingCode') {
                    // 证券代码
                    item.width = '10%';
                  }
                  if (item.dataIndex == 'reviewStatus') {
                    // 复核状态
                    item.width = '10%';
                  }
                  if (item.dataIndex == 'probabilityDefault') {
                    // 违约概率(PD)
                    item.width = '12%';
                    item.align = 'right';
                    item.render = (text, record, index) => {
                      if (text === null || text === undefined) {
                        return '--';
                      } else {
                        if (isNaN(text)) {
                          return text;
                        } else {
                          return (Number(text) * 100).toFixed(2) + '%'; //数字默认无小数位，需要小数位自行传入
                        }
                      }
                    };
                  }
                  if (item.dataIndex == 'lossGivenDefault') {
                    // 违约损失率(LGD)
                    item.width = '12%';
                    item.align = 'right';
                    item.render = (text, record, index) => {
                      if (text === null || text === undefined) {
                        return '--';
                      } else {
                        if (isNaN(text)) {
                          return text;
                        } else {
                          return Math.floor(Number(text) * 100).toFixed(0) + '%'; //数字默认无小数位，需要小数位自行传入
                        }
                      }
                    };
                  }
                  if (item.dataIndex == 'expectedCreditLosses') {
                    // 预期信用损失比例(ECL)
                    item.width = '14%';
                    item.align = 'right';
                    item.render = (text, record, index) => {
                      if (text === null || text === undefined) {
                        return '--';
                      } else {
                        if (isNaN(text)) {
                          return text;
                        } else {
                          return (Number(text) * 100).toFixed(4) + '%'; //数字默认无小数位，需要小数位自行传入
                        }
                      }
                    };
                  }
                });
              this.setState({
                columns: data.columns,
                dataSource: data.dataSource,
              });
            }
          },
        });
      },
    );
  };

  // 勾选事件
  onSelectChange = (selectedRowKeys) => {
    // 存放勾选中未复核的数据id
    let resultArr = [];
    // 存放勾选中已复核的数据id
    let exportResultArr = [];

    this.setState({ selectedRowKeys }, () => {
      if (this.state.selectedRowKeys?.length > 0) {
        // 一键确认 是否置灰逻辑处理 resultArr:存放勾选中 状态为未复核的数据
        this.state.selectedRowKeys &&
          this.state.selectedRowKeys.length &&
          this.state.selectedRowKeys.forEach((item) => {
            this.state.dataSource &&
              this.state.dataSource.length &&
              this.state.dataSource.forEach((dataItem) => {
                if (dataItem.id == item && dataItem.reviewStatus == '未复核') {
                  resultArr.push(item);
                }
                if (dataItem.id == item && dataItem.reviewStatus == '已复核') {
                  exportResultArr.push(item);
                }
              });
          });
        this.setState({
          checkConfirmArr: resultArr,
          exportArr: exportResultArr,
          isCheck: resultArr.length ? true : false,
          isExportCheck: exportResultArr.length ? true : false,
        });
      } else {
        this.setState({
          isCheck: false,
          isExportCheck: false,
          checkConfirmArr: [],
          exportArr: [],
        });
      }
    });
  };
  // 编辑事件
  editItem = (recordId) => {
    this.setState(
      {
        isEdit: true, // 表格处于编辑状态
      },
      () => {
        this.changeColumns(recordId, 'editable');
      },
    );
  };
  // 保存事件
  saveItem = (record) => {
    const {
      form: { validateFields },
    } = this.props;
    validateFields((err, fieldsValue) => {
      if (!err) {
        this.props.dispatch({
          type: 'nonstandardValueReviewM/changeRatioValue',
          payload: {
            id: record.id,
            assetType: record.assetType, //资产类型
            probabilityDefault: (Number(fieldsValue.probabilityDefault) / 100).toFixed(4), //违约概率
            lossGivenDefault: (Math.floor(fieldsValue.lossGivenDefault) / 100).toFixed(2), //违约损失率
            expectedCreditLosses: this.state.expectedCreditLossesTemp, //预期信用损失比例(ECL)
          },
          callback: (type) => {
            if (type == 'success') {
              this.getTableData();
              this.setState({ isEdit: false });
            }
          },
        });
      } else {
        message.error('请输入估值结果');
      }
    });
  };
  // 取消事件
  cancelItem = (recordId) => {
    this.setState({ isEdit: false });
    this.changeColumns(recordId, 'none');
  };
  // 编辑状态时,违约概率的change事件,改变信用损失比例的值
  probabilityChange = (e) => {
    const { form } = this.props;
    if (!isNaN(e)) {
      let tempDataSource = _.cloneDeep(this.state.dataSource);
      let resultNum = Number((e * form.getFieldValue('lossGivenDefault')) / 10000);
      tempDataSource?.forEach((item) => {
        if (item.id == this.state.editDataSource.id) {
          item.expectedCreditLosses = resultNum;
        }
      });
      this.setState({
        dataSource: tempDataSource,
        expectedCreditLossesTemp: resultNum,
      });
    }
  };
  // 编辑状态时,违约损失率的change事件
  lossGivenChange = (e) => {
    const { form } = this.props;
    if (!isNaN(e)) {
      let tempDataSource = _.cloneDeep(this.state.dataSource);
      let resultNum = Number((Math.floor(e) * form.getFieldValue('probabilityDefault')) / 10000);
      tempDataSource?.forEach((item) => {
        if (item.id == this.state.editDataSource.id) {
          item.expectedCreditLosses = resultNum;
        }
      });
      this.setState({
        dataSource: tempDataSource,
        expectedCreditLossesTemp: resultNum,
      });
    }
  };
  // 更改columns，添加和更改属性来实现可编辑单元格
  changeColumns = (id, type) => {
    const { columns, dataSource, editDataSource } = this.state;
    const arr = dataSource.filter((item) => item.id == id); //根据id查找该条数据
    const index = dataSource.findIndex((item) => item.id == id); //查找数据位置
    if (type == 'editable') {
      // 编辑状态，估值结果变为可编辑的单元格
      // 编辑前保存该数据，防止取消后数据更改
      let editDataSource = _.cloneDeep(arr[0]);
      this.setState({
        editDataSource: editDataSource,
      });

      dataSource.map((item) => (item.isDisabled = true)); // 当有一条数据处于编辑状态时，其他数据不可编辑
      arr[0].isEdit = true;
      dataSource.splice(index, 1, arr[0]);
    } else if (type == 'none') {
      // 非编辑状态，还原
      arr[0].isEdit = undefined;
      arr[0].probabilityDefault = editDataSource.probabilityDefault;
      arr[0].lossGivenDefault = editDataSource.lossGivenDefault;
      arr[0].expectedCreditLosses = editDataSource.expectedCreditLosses;
      dataSource.map((item) => (item.isDisabled = undefined));
      dataSource.splice(index, 1, arr[0]);
    }
    columns &&
      columns.length &&
      columns.forEach((item) => {
        if (item.key == 'probabilityDefault') {
          // 违约概率(PD)
          item.render = (text, record, index) => {
            if (text === null || text === undefined) {
              return '--';
            } else {
              if (isNaN(text)) {
                return text;
              } else {
                if (record.isEdit) {
                  return (
                    <InputNumberC
                      form={this.props.form}
                      dataIndex={'probabilityDefault'}
                      initialValue={Number(record.probabilityDefault) * 100}
                      splitStyle={true}
                      min={0}
                      max={100}
                      precision={2}
                      unit={'%'}
                      onChange={(e) => this.probabilityChange(e)}
                      rules={[{ required: true, message: ' ' }]}
                    />
                  );
                } else {
                  return (Number(text) * 100).toFixed(2) + '%';
                }
              }
            }
          };
        }
        if (item.key == 'lossGivenDefault') {
          // 违约损失率(LGD)
          item.render = (text, record, index) => {
            if (text === null || text === undefined) {
              return '--';
            } else {
              if (isNaN(text)) {
                return text;
              } else {
                if (record.isEdit) {
                  return (
                    <InputNumberC
                      form={this.props.form}
                      dataIndex={'lossGivenDefault'}
                      initialValue={Math.floor(Number(record.lossGivenDefault) * 100)}
                      precision={0}
                      splitStyle={true}
                      min={0}
                      max={100}
                      unit={'%'}
                      onChange={this.lossGivenChange}
                      rules={[{ required: true, message: ' ' }]}
                      formatter={(value) => {
                        return value.replace(/[^\d]/g, '');
                      }}
                      parser={(value) => {
                        return value.replace(/[^\d]/g, '');
                      }}
                    />
                  );
                } else {
                  return Math.floor(Number(text) * 100).toFixed(0) + '%';
                }
              }
            }
          };
        }
      });
    this.setState({
      columns,
    });
  };
  // 一键确认
  confirmClick = () => {
    const { checkConfirmArr, dataSource } = this.state;
    // 勾选的数据中是否有正在编辑的状态
    let flag = false;
    checkConfirmArr &&
      checkConfirmArr.length &&
      checkConfirmArr.forEach((selectItem) => {
        dataSource &&
          dataSource.length &&
          dataSource.forEach((item) => {
            if (item.id == selectItem && item.isEdit) {
              flag = true;
            }
          });
      });
    if (!flag) {
      this.props.dispatch({
        type: 'nonstandardValueReviewM/ratioGroupConfirm',
        payload: checkConfirmArr,

        callback: (type) => {
          if (type == 'success') {
            this.getTableData();
          }
        },
      });
    } else {
      // 编辑状态,
      message.warning('请保存您编辑的信息后再操作。');
    }
  };
  // 导出
  export = () => {
    const { exportArr, dataSource } = this.state;
    // 勾选的数据中是否有正在编辑的状态
    let flag = false;
    exportArr &&
      exportArr.length &&
      exportArr.forEach((selectItem) => {
        dataSource &&
          dataSource.length &&
          dataSource.forEach((item) => {
            if (item.id == selectItem && item.isEdit) {
              flag = true;
            }
          });
      });

    if (!flag) {
      const params = {
        reviewDatas: exportArr.join(),
      };
      exportFile('api/v1/nonstandardECL/exportNonstandardECLCfgList', params);
    } else {
      // 编辑状态,
      message.warning('请保存您编辑的信息后再操作。');
    }
  };
  // info提示
  infoContent = () => {
    return <div>当天的估值结果会在每日日终07:15提供。</div>;
  };
  render() {
    const { columns, dataSource, selectedRowKeys, isCheck, isExportCheck } = this.state;
    const { setId } = this.props;
    if (columns?.length && columns[columns?.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        width: '10%',
        operates: [
          {
            title: '编辑',
            onClick: (record, index) => {
              this.editItem(record.id);
            },
            rules: {
              // 某条数据处于编辑状态，其他数据操作被禁用
              disabled: {
                items: [{ key: 'isDisabled', value: [undefined], relation: ['!='] }],
              },
              // 点击编辑时隐藏编辑和删除按钮，展示保存和取消按钮
              hide: {
                relation: 'or',
                items: [
                  { key: 'isEdit', value: [undefined], relation: ['!='] },
                  // 未复核的数据才可以编辑
                  { key: 'reviewStatus', value: ['已复核'], relation: ['='] },
                ],
              },
            },
          },
          {
            title: '保存',
            onClick: (record, index) => {
              this.saveItem(record);
            },
            rules: {
              // 点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
              hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['='] }] },
            },
          },
          {
            title: '取消',
            onClick: (record, index) => {
              this.cancelItem(record.id);
            },
            rules: {
              // 点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
              hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['='] }] },
            },
          },
        ],
      });
    }
    // 勾选
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    return (
      <div>
        <div className={myStyle.operateInfo}>
          <div>
            <Popconfirm title={'是否确认？'} icon={<QuestionCircleOutlined />} onConfirm={this.confirmClick}>
              <PrimaryC title='一键确认' disabled={!isCheck} />
            </Popconfirm>
          </div>
          <div className={myStyle.infoTip}></div>
          <div style={{ marginRight: '10px' }}>
            <Popconfirm title={'仅导出"已复核"的数据。'} icon={<QuestionCircleOutlined />} onConfirm={this.export}>
              <PrimaryGhostC title={'导出'} disabled={!isExportCheck} />
            </Popconfirm>
          </div>
        </div>
        <div>
          <TableC
            columns={columns}
            dataSource={dataSource}
            hidePage={true}
            rowKey='id'
            scroll={{ x: '100%',y:600}}
            rowSelection={rowSelection}
            bigTable={true}
          />
        </div>
      </div>
    );
  }
}
